<?php
/**
 * Index.php - The Website entrance file
 *
 * NMIT BIT Project - Infinity - A 3D Website using WebGL & HTML5 Technology
 * Infinity Grid Version 
 * Version: 1.0 Beta 2
 *
 * Author: William Liu <qzliuyuzou@gmail.com> <lyzdev@gmail.com>
 *
 * Required Server Version:
 *  PHP5 or higher
 *  MySQL 5 or higher
 *
 * Required Browser Version:
 *  Google Chrome 9 or higher
 *  Mozilla Firefox 4 Beta or higher
 *  *Apple Safari
 *
 * Copyright (c) 2011, William Liu All rights reserved.
 * Infinity is an open source 3D website project
 * Under Apache License 2.0 
 * http://www.lyzsoft.cn
 * http://7cloud.wordpress.com
 *
 * Project Starting date: 9/3/2011
 * Update Date 1: 19/3/2011
 * Update Date 2: 24/3/2011
 * Update Date 3: 5/4/2011 -- WebGL Cloud test
 * Update Date 4: 6/4/2011
 * Update Date 5: 26/4/2011
 * Update Date 6: 27/4/2011
 * Update Date 7: 30/4/2011
 * Update Date 8: 1/5/2011
 * Update Date 9: 2/5/2011 -- Try to render text
 *                            Try to solve performance(there are two different render modle: 2d canvas render and WebGL render)
 * Update Date 10: 4/5/2011 Merge textrender.php and index.php, delete previous 3D codes
 * Update Date 11: 5/5/2011 Change Styles
 * Update Date 12: 11/5/2011
 * Update Date 13: 15/5/2011
 * Update Date 14: 5/6/2011 - Beta 2
 *
**/
?>

<?php
// file include check
define('INCLUDE_CHECK',1);
require_once('connection.php');
require_once('function.php');
//require_once('Archive/pagenavi.php');

$msgQuery = mysql_query("(select * from msg order by id desc)limit 15")
or die("the fail database query is fail!");
while ($msgRow = mysql_fetch_array($msgQuery)) {
	$msgList .= formatSay($msgRow[content],$msgRow[addtime],$msgRow[avatarID]);
}
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="keywords" content="WebGL,Three.js,HTML5,3D,php,jquery" />
<meta name="description" content="WebGL,Three.js,HTML5,3D,php,jquery"/>

<title>Infinity - The New Wedsite Revolution</title>

<?php
echo "<script language=\"JavaScript\">\n";
$counter = 1;
$threeMsgQuery = mysql_query("select content from msg order by id desc") or die(mysql_error());
//$threeMsgRow = mysql_fetch_array()

while ($threeMsgRow = mysql_fetch_array($threeMsgQuery))
{
	$threeMsg = stripslashes(str_replace("\r"," ",(str_replace("\n"," ",$threeMsgRow[content]))));
	echo "var outputmsg" . $counter . " =  \"" . $threeMsg . "\";\n";
	$counter ++;
	}
echo "var counter = " . $counter . ";\n";
echo "</script>";
?>


  <script type="text/javascript" src="js/jquery.js"></script>
  
  <!--UI control js-->
  <script type="text/javascript" src="js/global.js"></script>
  
  <!--<script type="text/javascript" src="js/zoom.js"></script>-->
  
  <!--WebGL JS Library JS
  <script type="text/javascript" src="js/ThreeWebGL.js"></script>
  <script type="text/javascript" src="js/ThreeExtras.js"></script>
  -->
  <script type="text/javascript" src="js/Three.js"></script>
  
  <script type="text/javascript" src="js/Detector.js"></script>
  <script type="text/javascript" src="js/RequestAnimationFrame.js"></script>
  <!-- Performance Monitor
  This class provides a simple info box that will help you monitor your code performance.
  
  FPS Frames rendered in the last second. The higher the number the better.
  MS Milliseconds needed to render a frame. The lower the number the better.
  MEM Mbytes of memory allocated. Make sure it doesn't keep incrementing. (Webkit-based browsers only)
  
  Reference: https://github.com/mrdoob/stats.js/blob/master/README.md
  
  ###
  -->
  <script type="text/javascript" src="js/Stats.js"></script>

  <!--GUI lib sources-->
  <link href='js/gui/GUI.css' media='screen' rel='stylesheet' type='text/css'/>
  <script type='text/javascript' src='js/gui/GUI.js'></script>
  <script type='text/javascript' src='js/gui/ControllerNumberSlider.js'></script>
  <script type='text/javascript' src='js/gui/Controller.js'></script>
  <script type='text/javascript' src='js/gui/ControllerBoolean.js'></script>
  <script type='text/javascript' src='js/gui/ControllerString.js'></script>
  <script type='text/javascript' src='js/gui/ControllerFunction.js'></script>
  <script type='text/javascript' src='js/gui/ControllerNumber.js'></script>

  <!--GUI function sources-->
  <script type='text/javascript' src='js/gui/improvedNoise.js'></script>
  <script type='text/javascript' src='js/gui/prettify.js'></script>
  <script type='text/javascript' src='js/infinityUI.js'></script>


<script type='text/javascript'>
window.onload = function() {

  prettyPrint();

  var fizzyText = new FizzyText('Infinity');
  var gui = new DAT.GUI();

  // Text field
  gui.add(fizzyText, 'message');

  // Sliders with min + max
  gui.add(fizzyText, 'maxSize').min(0.5).max(7);
  gui.add(fizzyText, 'growthSpeed').min(0.01).max(1).step(0.05);
  // shorthand for min/max/step
  gui.add(fizzyText, 'speed', 0.1, 2, 0.05); 

  // Sliders with min, max and increment.
  gui.add(fizzyText, 'noiseStrength', 10, 100, 5);

  // Boolean checkbox
  gui.add(fizzyText, 'displayOutline');

  // Fires a function called 'explode'
  gui.add(fizzyText, 'explode').name('Oops! Hit me!');

  // Javascript for documentation
  getCollapsables();
  handleListening();
};

function toggle(e) {

  var collapsable = this.childNodes[3],
	  wrapper = collapsable.childNodes[1];

  if (this.className === 'collapsed') {
	this.className = 'expanded';
	collapsable.style.height = wrapper.clientHeight + 'px';
  } else {
	this.className = 'collapsed';
	collapsable.style.height = '0px';
  }
}

function getCollapsables() {

  if (document.getElementsByClassName == undefined) {
	document.getElementsByClassName = function(className) {
	  var hasClassName = new RegExp('(?:^|\\s)' + className + '(?:$|\\s)');
	  var allElements = document.getElementsByTagName('*');
	  var results = [];

	  var element;
	  for (var i = 0; (element = allElements[i]) != null; i++) {
		var elementClass = element.className;
		if (elementClass && elementClass.indexOf(className) != -1 &&
			hasClassName.test(elementClass))
		  results.push(element);
	  }

	  return results;
	};
  }

  collapsed = document.getElementsByClassName('collapsed');
  expanded = document.getElementsByClassName('expanded');
}

function handleListening() {

  for (var i = 0; i < collapsed.length; i++) {
	collapsed[i].addEventListener('click', toggle, false);
  }

  for (var j = 0; j < expanded.length; j++) {
	expanded[i].addEventListener('click', toggle, false);
  }
}
</script>


<!--Style Sheet for Infinity-->
<link rel="stylesheet" type="text/css" href="style.css"/>
<!--END::Style Sheet for Infinity-->

</head>

<body>

<div id="header">
<div id='fizzyLogo'></div>
<div id="logo">
  <h1>
      <a href="#" title="Welcome to Infinity">Infinity</a>
  </h1>
</div>
<script type='text/javascript'>
var logo2D = document.getElementById('logo');
var threeEnabled = true;
if (!Detector.webgl) {
	threeEnabled = false;
	logo2D.style.display = "";
	}
	else
	{
		logo2D.style.display = "none";
		}
</script>
</div>

<div id="main">
  <div class="content">
    <form id="txtarea">
      <h3><span class="counter">140</span>Want to say something...</h3>      
      <textarea name="comment" id="comment" class="input" tabindex="1" rows="5" cols="40"></textarea>
      <input name="submit" type="submit" id="submit" class="push" value="Push">
    </form>
    <span class="warning" id="warning" style="height:20px"></span>
    <div class="clear"></div>
    
    <table id="msgwrap" class="msglist" cellspacing="0">
      <thead class="commentheadbar">
          <tr>
              <th></th>
              <th class="msgmanagetitle">Other People Say</th>
              <th></th>
          </tr>
      </thead>
      <tbody id="msglist" class="msglist">
        <?php echo $msgList;?>
      </tbody>
    </table>
    <div class="clear"></div>
    <script type="text/javascript">
	//WebGL detector, check the browser
	if ( !Detector.webgl ) Detector.addGetWebGLMessage();
	</script>
  </div>
</div>


<script type="text/javascript"> 
/*
Original Code by Theo Armour 2011-03-25
Modify by William Liu 2011-05-04
*/

var container;

var camera, scene, renderer;

var mouseX = 0,
    mouseY = 0;

var windowHalfX = window.innerWidth / 2;
var windowHalfY = window.innerHeight / 2;

//set stats monitor enable or disable (true/false)
var statsEnabled = true;
var statsMonitor = new Stats();

//camera position fix
var cameraDefult = 800;
//var cameraTargetDefultX = 0;
var displayWidth = window.innerWidth;
var displayHeight = window.innerHeight;
var cameraCurrent;
//var cameraTargetCurrentX;

//Zoom
var cameraFar = 1500;
var cameraNear = 100;

//camera target move
//var cameraTargetPX = 900;
//var cameraTargetNX = -900;

// camera position adjustment
function cameraAdjust() {
	
	if (displayWidth > 1900)
	{
		cameraCurrent = cameraDefult;
		}
	else
	{
		cameraCurrent = 500;
		}	
	}

// try to reload render *fail
//var checkSubmit = document.getElementById('submit')
/*
function reflashRender() {
	if (checkSubmit.onclick) {
		init();
		animate();
		}
	}
*/
// change camera position
cameraAdjust();
init();
animate();

function init() {

    container = document.createElement('div');
    document.body.appendChild(container);

    camera = new THREE.Camera(40, window.innerWidth / window.innerHeight, 1, 2000);
    camera.position.y = 0;
    camera.position.z = cameraCurrent;
    camera.target.position.x = 0;
    camera.target.position.y = 50;
    camera.target.position.z = 0;

    scene = new THREE.Scene();

    var object, material;

    object = new THREE.Mesh(new THREE.PlaneGeometry(1000, 1000, 50, 50), new THREE.MeshBasicMaterial({
        color: 0x666666,
        opacity: 0.5,
        wireframe: true
    }))
    object.position = {
        x: 0,
        y: -20,
        z: 0
    };
    object.rotation = {
        x: 1.57,
        y: 0,
        z: 0
    };

    scene.addObject(object);


	//Text objects
    var canvas = document.createElement("canvas");
    var context = canvas.getContext("2d");
    canvas.width = 600;
    canvas.height = 300;
    context.fillStyle = "#EA7D21";
    context.font = "60pt arial";
    context.textBaseline = "top";
	//void fillText(in DOMString text, in float x, in float y, [Optional] in float maxWidth);
    context.fillText(outputmsg1, 10, 0);

    var text = new THREE.MeshBasicMaterial({
        map: new THREE.Texture(canvas),
		opacity: 0.5,
        blending: THREE.BillboardBlending		
    });
    text.map.needsUpdate = true;

    var mesh = new THREE.Mesh(new THREE.PlaneGeometry(80, 40, 2, 2), text);
    mesh.position.x = 0;
    mesh.position.y = 50;
    mesh.position.z = 0;

	mesh.doubleSided = true;
    mesh.updateMatrix();
    scene.addObject(mesh);
	//Text Object end
	
	<?php
	if($counter > 1)
	{
		//echo "<script language=\"JavaScript\">\n";
		
		$objCounter = 2;
		
		while ($objCounter < $counter)
		{
			$positionX = rand(-400,400);
			$positionY = rand(10,150);
			$positionZ = rand(-350,100);
			
			echo "
			var canvas_".$objCounter." = document.createElement(\"canvas\");
			var context_".$objCounter." = canvas_".$objCounter.".getContext(\"2d\");
			canvas_".$objCounter.".width = 240;
			canvas_".$objCounter.".height = 120;
			context_".$objCounter.".fillStyle = \"#A1FF66\";
			context_".$objCounter.".font = \"40pt arial\";
			context_".$objCounter.".textBaseline = \"top\";
			context_".$objCounter.".fillText(outputmsg".$objCounter.", 10, 0);
		
			var text_".$objCounter." = new THREE.MeshBasicMaterial({
				map: new THREE.Texture(canvas_".$objCounter."),
				blending: THREE.BillboardBlending
			});
			text_".$objCounter.".map.needsUpdate = true;
		
			var mesh_".$objCounter." = new THREE.Mesh(new THREE.PlaneGeometry(60, 30, 2, 2), text_".$objCounter.");
			mesh_".$objCounter.".position.x = ".$positionX.";
			mesh_".$objCounter.".position.y = ".$positionY.";
			mesh_".$objCounter.".position.z = ".$positionZ.";
		
			mesh_".$objCounter.".doubleSided = true;
			mesh_".$objCounter.".updateMatrix();
			scene.addObject(mesh_".$objCounter.");
			";
			$objCounter ++;
		}
		
		/*echo "</script>";*/
	}
	?>

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.sortObjects = false;

    container.appendChild(renderer.domElement);
    
    if (statsEnabled)
    {
        statsMonitor.domElement.style.position = 'fixed';
        statsMonitor.domElement.style.top = '0px';
        statsMonitor.domElement.style.left = '0px';
        statsMonitor.domElement.style.zIndex = 100;
        container.appendChild( statsMonitor.domElement );
    }

    document.addEventListener('mousemove', onDocumentMouseMove, false);
	document.addEventListener('keypress', onDocumentKeyPress, false);
	//window.addEventListener( 'resize', onWindowResize, false );
}

function onDocumentMouseMove(event) {
    mouseX = (event.clientX - windowHalfX);
    mouseY = (event.clientY - windowHalfY);
}

function onDocumentKeyPress(event) {
	//key: w -> keycode: 119
	// keycode for chrome; charcode for ff
	if((event.keyCode == 119 || event.charCode == 119) && (cameraCurrent > cameraNear))
	{
		cameraCurrent -= 10;
		}
	//key: s -> keycode: 115
	else if((event.keyCode == 115 || event.charCode == 115) && (cameraCurrent < cameraFar))
	{
		cameraCurrent += 10;
		}
	/* Disable for some bugs reason
	//key: d -> keycode: 100
	else if((event.keyCode == 100 || event.charCode == 100) && (cameraTargetCurrentX < cameraTargetPX))
	{
		cameraTargetCurrentX += 10;
		}
	//key: a -> keycode: 97
	else if((event.keyCode == 97 || event.charCode == 97) && (cameraTargetCurrentX > cameraTargetNX))
	{
		cameraTargetCurrentX -= 10;
		}
	*/
}

/*
function onWindowResize(event) {
	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();
 
	renderer.setSize( window.innerWidth, window.innerHeight );
}
*/

function animate() {

    requestAnimationFrame(animate);

    //render();
	// performance control, if we cannot see the 3D objects do not render them
	//if (document.body.scrollTop > document.body.clientHeight - window.innerHeight - 950) {
      render();
    //}
	

    if ( statsEnabled )
    {
        statsMonitor.update();
    }
}


function render() {
	
	
    camera.position.x += (mouseX - camera.position.x) * 0.05;
    camera.position.y += (mouseY - camera.position.y) * 0.05;
	
	//zoom-in/out
	camera.position.z = cameraCurrent;
	
	//camera target x coordinate adjust
	//camera.target.position.x = cameraTargetCurrentX;

    // var timer = new Date().getTime() * 0.0001;
    // camera.position.x = Math.cos( timer ) * 800;
    // camera.position.z = Math.sin( timer ) * 800;

    for (var i = 1, l = scene.objects.length; i < l; i++) {
        var object = scene.objects[i];
        object.lookAt(camera.position);
    }

    renderer.render(scene, camera);
	//renderer.autoClear = true;
	//renderer.enableDepthBufferWrite(true);
}
</script>

<div id="footer">
    <p>Powered by William</p>
    <p><a href="admin.php">Admin Login</a> | <a href="readme.html">About</a></p>
</div>
<div class="clear"></div>

</body>
</html>